﻿using Magic.Oidc.MvcClient.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using OpenIddict.Client;
using Quartz;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace Magic.Oidc.MvcClient.Extensions
{
    public static class RegisterServices
    {
        public static WebApplicationBuilder SetupServices(this WebApplicationBuilder builder)
        {
            builder.Services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });

            builder.Services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/login";
                options.LogoutPath = "/logout";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(50);
                options.SlidingExpiration = false;
            });

            builder.Services.AddQuartz(options =>
            {
                options.UseMicrosoftDependencyInjectionJobFactory();
                options.UseSimpleTypeLoader();
                options.UseInMemoryStore();
            });

            builder.Services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);


            builder.Services.AddOpenIddict()
                .AddCore(options =>
                {
                    options.UseEntityFrameworkCore()
                           .UseDbContext<ApplicationDbContext>();
                    options.UseQuartz();
                })
                .AddClient(options =>
                {
                    options.AllowAuthorizationCodeFlow();

                    options.AddDevelopmentEncryptionCertificate()
               .AddDevelopmentSigningCertificate();

                    options.UseAspNetCore()
               .EnableStatusCodePagesIntegration()
               .EnableRedirectionEndpointPassthrough()
               .EnablePostLogoutRedirectionEndpointPassthrough();

                    // Register the System.Net.Http integration and use the identity of the current
                    // assembly as a more specific user agent, which can be useful when dealing with
                    // providers that use the user agent as a way to throttle requests (e.g Reddit).
                    options.UseSystemNetHttp()
               .SetProductInformation(typeof(Program).Assembly);

                    // Add a client registration matching the client application definition in the server project.
                    options.AddRegistration(new OpenIddictClientRegistration
                    {
                        Issuer = new Uri("https://localhost:7000/", UriKind.Absolute),
                        ClientId = "mvc",
                        ClientSecret = "901564A5-E7FE-42CB-B10D-61EF6A8F3654",
                        //Scopes = { Scopes.Email, Scopes.Profile,Scopes.Roles },
                        Scopes = { Scopes.Email, Scopes.Profile },

                        RedirectUri = new Uri("callback/login/local", UriKind.Relative),
                        PostLogoutRedirectUri = new Uri("callback/logout/local", UriKind.Relative)
                    });
                });
            builder.Services.AddHttpClient();
            // Add services to the container.
            builder.Services.AddRazorPages();
            builder.Services.AddControllersWithViews();

            // Register the worker responsible for creating the database used to store tokens.
            // Note: in a real world application, this step should be part of a setup script.
            builder.Services.AddHostedService<Worker>();
            return builder;
        }
    }
}
